package lumis.service.portalmanagement.xsleditor;

import java.io.ByteArrayOutputStream;

import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import lumis.portal.PortalContext;
import lumis.portal.PortalException;
import lumis.portal.PortalStringResource;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.controller.ControllerException;
import lumis.portal.manager.ManagerFactoryInternal;
import lumis.portal.presentation.layout.defaultlayout.AbstractPageBodyMiddleComponent;
import lumis.portal.servicecontainer.ServiceContainer;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.util.HtmlUtil;
import lumis.util.IResource;
import lumis.util.ITransaction;
import lumis.util.XmlUtil;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.util.string.AppendingStringBuffer;
import org.w3c.dom.Document;

/**
 * Injects the xsl components in the page. 
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
@SuppressWarnings("serial")
public class XsltResultPageBodyMiddleComponent extends AbstractPageBodyMiddleComponent 
{
	/**
	 * The constructor for the class.
	 * @param id component identifier.
	 * @since 6.0.0
	 */
	public XsltResultPageBodyMiddleComponent(String id) 
	{
		super(id);
	}
	
	@Override
	public CharSequence getHTMLFragment(MarkupStream markupStream, ComponentTag openTag) 
	{
		try
		{
			AppendingStringBuffer result = new AppendingStringBuffer(15000);
			
			result.append(renderResultsForm());
			
			result.append("<div class=\"cLumPage\">");
			result.append(renderXsltResult(PortalTransactionFactory.getCurrentTransaction()));
			result.append("</div>");
			return result;
		}
		catch (PortalException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Renders the result of the XSL.
	 * @param portalTransaction the current transaction.
	 * @return the Result
	 * @throws PortalException
	 * @since 6.0.0
	 */
	private String renderXsltResult(ITransaction portalTransaction) throws PortalException
	{
		IResource xslResource = new PortalStringResource();
		xslResource.addResourcePath("lumis/service/portalmanagement/xsleditor/strings/strings");

		try
		{
			String interfaceInstanceId = ((WebRequest)getRequest()).getHttpServletRequest().getParameter("interfaceInstanceId");
			
			String xslContent = ((WebRequest)getRequest()).getHttpServletRequest().getParameter("xslContent");
			if (xslContent == null || xslContent.trim().equals(""))
			{
				throw new PortalException("STR_XSL_NOT_SPECIFIED", xslResource);
			}
			
			// loads the xsl
			String filePath = ((WebRequest)getRequest()).getHttpServletRequest().getParameter("xslContentFilePath");
			Transformer transformer = ManagerFactoryInternal.getXslCacheManager().createTransformer(xslContent, filePath);
			
			// transform the xml
			Document responseDocument = XmlUtil.getDocumentFromFile(PortalContext.getDataPath("/sessions/" + SessionConfig.getCurrentSessionConfig().getUserSessionId() + "/" + interfaceInstanceId + "data.xml"));
			DOMSource domSource = new DOMSource(responseDocument);	
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			
			transformer.transform(domSource, new StreamResult(outputStream));
			
			// fix HTML output
			String outputHTML = outputStream.toString("UTF-8");
			outputHTML = HtmlUtil.fixInvalidHtmlPattern(outputHTML);
			
			outputHTML = ServiceContainer.removeNotConvertDynUrls(outputHTML);
			
			return outputHTML;
		}
		catch(PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			//logger.error("Error rendering results in style editor", e);
			throw new ControllerException("STR_TRANSFORMATION_EXCEPTION", xslResource, e);
		}
	}

	/**
	 * Renders the results form.
	 * @return the corresponding HTML code.
	 * @since 6.0.0
	 */
	private CharSequence renderResultsForm()
	{
		return "<form method=\"post\" name=\"ResultsForm\">\r\n" + 
				"	<input type=\"hidden\" id=\"xslContent\" name=\"xslContent\" />\r\n" + 
				"	<input type=\"hidden\" name=\"interfaceInstanceId\" />\r\n" + 
				"	<input type=\"hidden\" name=\"lumPageId\" value=\"\" />\r\n" + 
				"	<input type=\"hidden\" name=\"xslContentFilePath\" value=\"\" />\r\n" + 
				"	<script type=\"text/javascript\">\r\n" + 
				"	function sendXsl(strXslContent, interfaceInstanceId, pageId, xslFilePath)\r\n" + 
				"	{\r\n" + 				
				"		var pForm = document.forms['ResultsForm'];\r\n" + 
				"		pForm.elements[\"xslContent\"].value = strXslContent;\r\n" + 
				"		pForm.elements[\"interfaceInstanceId\"].value = interfaceInstanceId;\r\n" + 
				"		pForm.elements[\"lumPageId\"].value = pageId;\r\n" + 
				"		pForm.elements[\"xslContentFilePath\"].value = xslFilePath;\r\n" + 
				"		pForm.submit();\r\n" + 
				"	}\r\n" + 
				"	</script>\r\n" + 
				"</form>";
	}
}
